package pers.xx.sbm.controller;

import com.aspose.words.Document;
import com.aspose.words.License;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import pers.xx.sbm.base.Constants;
import pers.xx.sbm.base.Constants2;
import pers.xx.sbm.base.DailyConstant;
import pers.xx.sbm.enums.ResultEnum;
import pers.xx.sbm.utils.UUIDUtils;
import pers.xx.sbm.utils.file.FileUtil;
import pers.xx.sbm.vo.ResResult;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：xiexing
 * @description：文件处理Controller
 * @date ：2020/8/16 21:11
 */
@Controller
@RequestMapping("/file")
public class FileSystemController {

    @Autowired
    private Environment environment;


    /**
     * @description 文件上传
     * @author XieXing
     * @date 2020/8/16 21:13
     */

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public Object fileUpload(MultipartFile file, HttpServletResponse response) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
            String res = sdf.format(new Date());
            //上传路径
            String uploadPath = environment.getProperty("file.uploadPath");
            //原始名称
            String originalFilename = file.getOriginalFilename();
            //新的文件名称
            String newFileName = UUIDUtils.getUUID() + res + originalFilename.substring(originalFilename.lastIndexOf("."));
            //创建年月文件夹
            Calendar date = Calendar.getInstance();
            File dateDirs = new File(date.get(Calendar.YEAR)
                    + File.separator + (date.get(Calendar.MONTH) + 1));
            //新文件
            File newFile = new File(uploadPath + File.separator + dateDirs + File.separator + newFileName);
            //判断目标文件所在的目录是否存在
            if (!newFile.getParentFile().exists()) {
                //如果目标文件所在的目录不存在，则创建父目录
                newFile.getParentFile().mkdirs();
            }
            //将内存中的数据写入磁盘
            file.transferTo(newFile);
            //完整的url 换成正斜杠
            Object fileUrl = uploadPath + "/" + date.get(Calendar.YEAR) + "/" + (date.get(Calendar.MONTH) + 1) + "/" + newFileName;
            Map<String, Object> map = new HashMap();
            Map<String, Object> map2 = new HashMap();
            map.put("code", 0);    //0表示上传成功
            map.put("msg", "上传成功"); //提示消息
            //src返回图片上传成功后的下载路径，这里直接给绝对路径
            map2.put("path", fileUrl);
            map2.put("name", originalFilename);
            map.put("data", map2);
            return map;
        } catch (Exception e) {
            return new ResResult(ResultEnum.SYSTEM_ERR, e.getMessage());
        }
    }


    /**
     * @param sourceFileName 源文件名称 有的文件是上传后重命名保存的 如果要获取文件原来的名称 需要传入源文件名称
     * @param filePath       文件路径
     * @param isOnLine       是否在线打开
     * @description 文件下载
     * @author XieXing
     * @date 2020/8/16 21:37
     */
    @RequestMapping("/download")
    public void downLoad(String filePath, HttpServletResponse response, Boolean isOnLine, String sourceFileName) throws Exception {
        //文件为空
        if (StringUtils.isEmpty(filePath)) {
            response.sendError(404, "File not found!");
            return;
        }
        File f = new File(filePath);
        //文件不存在
        if (!f.exists()) {
            response.sendError(404, "File not found!");
            return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;
        response.reset(); // 非常重要
        String fileName = f.getName();
        if (!StringUtils.isEmpty(sourceFileName)) {
            fileName = new String(sourceFileName.replaceAll(" ", "").getBytes("GB2312"), "ISO8859-1");
        }
        if (isOnLine != null && isOnLine) { // 在线打开方式
            URL u = new URL("file:///" + filePath);
            response.setContentType(u.openConnection().getContentType());
            response.setHeader("Content-Disposition", "inline; filename=" + fileName);
            // 文件名应该编码成UTF-8
        } else { // 纯下载方式
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        }
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0)
            out.write(buf, 0, len);
        br.close();
        out.close();
    }


    /**
     * @description 文件删除
     * @author XieXing
     * @date 2021/2/3 11:08
     */
    @RequestMapping(value = "/deleteFile", method = RequestMethod.POST)
    @ResponseBody
    public ResResult deleteFile(String path) {
        if (StringUtils.isEmpty(path)) {
            return new ResResult(ResultEnum.PARAM_ERR, "文件路径为空");
        }
        File file = new File(path);
        if (file.isFile()) {
            file.delete();
            return new ResResult(ResultEnum.SUCCESS, "删除成功");
        } else {
            return new ResResult(ResultEnum.SYSTEM_ERR, "文件不存在");
        }
    }

    /**
     * @description html2doc html转换为word并下载
     * @author XieXing
     * @date 2021/12/27 18:01
     */
    @RequestMapping(value = "/html2Doc", method = RequestMethod.POST)
    public void html2Doc(String timestamp, String body, String areaName, HttpServletResponse response) throws Exception {
        commonDownload(timestamp, body, areaName + "2021年中小学幼儿园社会满意度调查报告", response, Constants.EXCEL_CSS + "");
    }


    /**
     * @description html2doc2 html转换为word并下载2
     * @author XieXing
     * @date 2021/12/27 18:01
     */
    @RequestMapping(value = "/html2Doc2", method = RequestMethod.POST)
    public void html2Doc2(String timestamp, String body, String areaName, HttpServletResponse response) throws Exception {
        commonDownload(timestamp, body, areaName + "2021年中小学生品德发展监测报告", response, Constants2.EXCEL_CSS + "");
    }


    private void commonDownload(String timestamp, String body, String areaName, HttpServletResponse response, String css) throws Exception {
        //取项目根目录
        String path = FileUtil.getCurProjectPath(this);
        //取时间戳命名文件夹，防止多用户同时下载时文件冲突
        String docPath = path + File.separator + "upload" + File.separator;

        File dir = new File(docPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //拼一个标准的HTML格式文档
        String content = "<html><head><meta charset='UTF-8'><style>" + css + "</style></head><body>" + body + "</body></html>";
        InputStream is = new ByteArrayInputStream(content.getBytes("UTF-8"));
        new License().setLicense(new FileInputStream(path + File.separator + "license.xml"));
        Document doc = new Document(is);
        DailyConstant.addOuline(doc);
        String fileName = areaName + timestamp + ".docx";
        String filePath = docPath + fileName;
        doc.save(filePath);
        downLoad(filePath, response, false, fileName);
    }
}
